package com.test.burnincash.activity_fragment_burnin.base_burnin;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import com.test.burnincash.R;
import com.test.burnincash.activity_fragment_burnin.loan_burnin.LoanMainActivity_burnin;
import com.test.burnincash.bean_burnin.config_info_burnin.AppShowInfo_burnin;
import com.test.burnincash.bean_burnin.config_info_burnin.AppShowPermissions_burnin;
import com.test.burnincash.util_burnin.PermissionUtil_burnin;
import com.test.burnincash.util_burnin.helper_burnin.ActivityHelper_burnin;
import com.test.burnincash.util_burnin.http_burnin.HttpManager_burnin;
import com.test.burnincash.util_burnin.http_burnin.HttpPresenter_burnin;

import java.util.ArrayList;
import java.util.List;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public abstract class BaseActivity_burnin extends AppCompatActivity implements EasyPermissions.PermissionCallbacks, EasyPermissions.RationaleCallbacks {

    private Toast toast_burnin;

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {}

    //权限拒绝
    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).build().show();
        }
    }

    @Override
    public void onRationaleDenied(int requestCode) {
        finish();
    }

    //页面埋点
    public void recordPagePauseEvent_burnin() {
        //保存埋点
        String activityName = getClass().getSimpleName();
        if (!TextUtils.isEmpty(activityName)) {
            HttpManager_burnin.getInstance().saveUserBuriedPoint((activityName + "_END").toUpperCase());
        }
    }

    //处理用户流程状态
    public void onUserProcessResponse_burnin() {
        startActivityForSingleTop_burnin(LoanMainActivity_burnin.class);
    }

    public void showToastOnUiThread_burnin(String text) {
        runOnUiThread(() -> showToast_burnin(text));
    }

    @Override
    protected void onResume() {
        super.onResume();
        HttpPresenter_burnin.getInstance().setActivity(this);
        recordPageResumeEvent_burnin();
    }

    public void showToast_burnin(String text) {
        if (toast_burnin == null) toast_burnin = Toast.makeText(this, text, Toast.LENGTH_SHORT);
        else toast_burnin.setText(text);
        toast_burnin.show();
    }

    public <T extends BaseActivity_burnin> void startActivityForSingleTop_burnin(Class<T> activityClass) {
        Intent intent = new Intent(this, activityClass);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity_burnin(activityClass);
        finish();
    }

    public void setBackBtn_burnin(View btnView) {
        btnView.setOnClickListener(view -> onBackPressed());
    }

    //页面埋点
    public void recordPageResumeEvent_burnin() {
        //保存埋点
        String activityName = getClass().getSimpleName();
        if (!TextUtils.isEmpty(activityName)) {
            HttpManager_burnin.getInstance().saveUserBuriedPoint((activityName + "_START").toUpperCase());
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View view = getCurrentFocus();
            if (view != null) {
                if (ActivityHelper_burnin.canHideKeyboard(view, ev)) {
                    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (inputMethodManager != null) {
                        ActivityHelper_burnin.hideKeyboard(this);
                        EditText editText = (EditText) view;
                        editText.clearFocus();
                    }
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        return getWindow().superDispatchTouchEvent(ev) || onTouchEvent(ev);
    }

    /**
     * 同意所有权限后回调，留给子类实现
     */
    protected void onLaunchPermissionsAllPass_burnin() {}

    public <T extends BaseActivity_burnin> void startActivity_burnin(Class<T> activityClass) {
        startActivity(new Intent(this, activityClass));
    }

    //权限申请通过后执行
    @RequiresApi(api = Build.VERSION_CODES.Q)
    @AfterPermissionGranted(PermissionUtil_burnin.REQ_CODE_PERMISSIONS)
    public void onEasyPermissionsAllPass() {
        Log.d(this.getClass().getSimpleName(), "on permissions all pass");
        onLaunchPermissionsAllPass_burnin();
    }


    @Override
    protected void onPause() {
        super.onPause();
        HttpPresenter_burnin.getInstance().setActivity(null);
        recordPagePauseEvent_burnin();
    }

    //检测权限并申请未获取的权限
    public void requestLaunchPermissions_burnin(String[] permissions) {
        EasyPermissions.requestPermissions(this, getString(R.string.launch_permissions), PermissionUtil_burnin.REQ_CODE_PERMISSIONS, permissions);
    }

    /**
     * 是否需要检查权限，留给子类实现
     * 默认需要检查
     */
    protected boolean onCheckLaunchPermissions_burnin() {
        return true;
    }

    @Override
    public void onRationaleAccepted(int requestCode) {
        if (AppShowInfo_burnin.getInstance().getPermissions().length==0) return;
        if (!PermissionUtil_burnin.checkLaunchPermissions(this, AppShowInfo_burnin.getInstance().getPermissions()))
            requestLaunchPermissions_burnin(AppShowInfo_burnin.getInstance().getPermissions());
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
        if (requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE) requestLaunchPermissions_burnin(AppShowInfo_burnin.getInstance().getPermissions());
    }

}